<!DOCTYPE html>
<html lang="zh-cn">
<meta http-equiv="Content-Type" content="text/html; charset=utf-8"/>

<head>
    <title>网页计算器</title>
    <style>
        input[type=text], button {
            padding: 10px;
            font-size: 24px;
            margin: 5px;
            border-radius: 5px;
            border: none;
        }

        button {
            background-color: #4CAF50;
            color: white;
        }
    </style>
</head>
<body>
<h1>网页计算器</h1>
<input type="text" id="result" placeholder="0">
<br>
<button onclick="clearResult()">C</button>
<button onclick="calculate('/')">/</button>
<button onclick="calculate('*')">*</button>
<br>
<button onclick="addNumber(7)">7</button>
<button onclick="addNumber(8)">8</button>
<button onclick="addNumber(9)">9</button>
<button onclick="calculate('-')">-</button>
<br>
<button onclick="addNumber(4)">4</button>
<button onclick="addNumber(5)">5</button>
<button onclick="addNumber(6)">6</button>
<button onclick="calculate('+')">+</button>
<br>
<button onclick="addNumber(1)">1</button>
<button onclick="addNumber(2)">2</button>
<button onclick="addNumber(3)">3</button>
<button onclick="calculate('=')">=</button>
<br>
<button onclick="addNumber(0)">0</button>
<button onclick="addDecimalPoint()">.</button>
</body>
<script>
    let result = document.getElementById("result");

    function addNumber(num) {
        if (result.value == "0") {
            result.value = num.toString();
        } else {
            result.value += num.toString();
        }
    }

    function addDecimalPoint() {
        if (!result.value.includes(".")) {
            result.value += ".";
        }
    }

    function clearResult() {
        result.value = "0";
    }

    function calculate(operator) {
        let expression = result.value;

        if (expression.endsWith("+") || expression.endsWith("-") || expression.endsWith("*") || expression.endsWith("/")) {
            expression = expression.slice(0, -1);
        }

        switch (operator) {
            case "/":
                if (expression.endsWith("/0")) {
                    result.value = "Error";
                } else {
                    result.value = eval(expression);
                }
                break;
            case "*":
                result.value = eval(expression);
                break;
            case "+":
                result.value = eval(expression);
                break;
            case "-":
                result.value = eval(expression);
                break;
            case "=":
                result.value = eval(expression);
                break;
        }

        if (typeof (result.value) === "number" && result.value % 1 !== 0) {
            result.value = parseFloat(result.value.toFixed(4));
        }
    }
</script>

</html>